package com.dw.gui.panel.record;

import com.dw.dao.record.MedicalRecordDao;
import com.dw.model.user.Doctor;
import com.dw.model.record.MedicalRecord;
import com.dw.util.UIUtil;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.sql.SQLException;
import java.util.List;

public class SupplyRecordPanel extends JPanel {
    private final MedicalRecordDao recordDao = new MedicalRecordDao();
    private MedicalRecordTableModel tableModel = new MedicalRecordTableModel();
    private JButton btnRefresh;
    private JButton btnWithdraw;
    private JTable recordTable;

    private Doctor doctor;

    public SupplyRecordPanel(Doctor doctor) {
        this.doctor = doctor;
        initUI();
        loadData();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        titlePanel.setBackground(Color.WHITE);
        titlePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        titlePanel.add(UIUtil.createTitleLabel("病案供应管理"));

        // 工具栏
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolPanel.setBackground(Color.WHITE);
        btnRefresh = UIUtil.createButton("刷新列表");
        btnRefresh.addActionListener(e -> refreshData());
        toolPanel.add(btnRefresh);
        btnWithdraw = UIUtil.createButton("撤回病案");
        btnWithdraw.setEnabled(false); // 初始不可用
        btnWithdraw.addActionListener(e -> withdrawSelected());
        toolPanel.add(btnWithdraw);

        // 表格配置
        recordTable = UIUtil.createTable(tableModel);
        recordTable.setRowHeight(30);
        recordTable.getSelectionModel().addListSelectionListener(_ -> updateButtonState());

        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        contentPanel.add(toolPanel, BorderLayout.NORTH);
        contentPanel.add(new JScrollPane(recordTable), BorderLayout.CENTER);

        add(titlePanel, BorderLayout.NORTH);
        add(contentPanel, BorderLayout.CENTER);
    }

    private void updateButtonState() {
        int selectedRow = recordTable.getSelectedRow();
        btnWithdraw.setEnabled(selectedRow != -1);
    }


    public void refreshData() {
        new SwingWorker<List<MedicalRecord>, Void>() {
            @Override
            protected List<MedicalRecord> doInBackground() throws SQLException {
                return recordDao.getAllActiveRecords();
            }
            @Override
            protected void done() {
                try {
                    tableModel.setData(get());
                } catch (Exception e) {
                    UIUtil.showError(SupplyRecordPanel.this,
                            "刷新失败：" + e.getMessage(), "错误");
                }
            }
        }.execute();
    }

    private void loadData() {
        try {
            List<MedicalRecord> records = recordDao.getAllActiveRecords();
            tableModel.setData(records);
        } catch (SQLException e) {
            UIUtil.showError(this, "加载病案失败: " + e.getMessage(), "数据库错误");
        }
    }

    private void withdrawSelected() {
        int selectedRow = recordTable.getSelectedRow();
        if (selectedRow == -1) return;

        int recordId = (int) tableModel.getValueAt(selectedRow, 0);
        if (UIUtil.showConfirm(this, "确定要撤回病案 #" + recordId + "吗？", "确认撤回")) {
            new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    recordDao.withdrawRecord(recordId);
                    return null;
                }

                @Override
                protected void done() {
                    try {
                        get();
                        refreshData();
                    } catch (Exception ex) {
                        UIUtil.showError(SupplyRecordPanel.this,
                                "撤回失败：" + ex.getMessage(), "系统错误");
                    }
                }
            }.execute();
        }
    }

    static class MedicalRecordTableModel extends AbstractTableModel {
        private List<MedicalRecord> data;
        private final String[] COLUMNS = {"病案号", "患者姓名", "入院日期", "诊断结果"};

        public void setData(List<MedicalRecord> data) {
            this.data = data;
            fireTableDataChanged();
        }

        @Override
        public int getRowCount() {
            return data != null ? data.size() : 0;
        }

        @Override
        public int getColumnCount() {
            return COLUMNS.length;
        }

        @Override
        public String getColumnName(int column) {
            return COLUMNS[column];
        }

        @Override
        public Object getValueAt(int row, int column) {
            MedicalRecord record = data.get(row);
            return switch (column) {
                case 0 -> record.getId();
                case 1 -> record.getPatientId();
                case 2 -> record.getAdmissionDate();
                case 3 -> record.getDiagnosis();
                default -> null;
            };
        }
    }
}